package com.locust.system.web.controller;

import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.locust.base.common.base.web.support.BaseResult;
import com.locust.base.common.base.web.support.controller.BaseController;
import com.locust.oss.aliyun.client.AliyunOSSClient;
import com.locust.oss.common.aliyun.FilePage;


/**
 * 阿里云 OSS
 * @author yhaoquan
 *
 */
@RestController
@RequestMapping(value = "/api/system/oss/aliyun")
public class AliyunOSSController extends BaseController {

	@Autowired
	private AliyunOSSClient ossClient;
	
	@PostMapping(value = "/upload")
	public Object upload(HttpServletRequest request, String bucketName, String prefixName) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request ;
		try {
			//取得MultiValueMap集合
			MultiValueMap<String,MultipartFile> multiFileMap = multipartRequest.getMultiFileMap() ;
			Set<Entry<String, List<MultipartFile>>> entrySet = multiFileMap.entrySet() ;
			for (Entry<String, List<MultipartFile>> entry : entrySet) {
				
				//获取MultipartFile集合
				List<MultipartFile> multipartFiles = entry.getValue() ;
				for (MultipartFile multipartFile : multipartFiles) {
					this.ossClient.upload(bucketName, multipartFile.getBytes(), multipartFile.getOriginalFilename(), prefixName) ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return BaseResult.failure() ;
	}
	
	@GetMapping(value = "/delete")
	public Object delete(String bucketName, String key) {
		this.ossClient.delete(bucketName, key) ;
		return BaseResult.ok() ;
	}
	
	@GetMapping(value = "/deleteBatch")
	public Object deleteBatch(String bucketName, String keys) {
		this.ossClient.deleteBatch(bucketName, keys);
		return BaseResult.ok() ;
	}
	
	@GetMapping(value = "/buckets")
	public Object buckets() {
		return this.ossClient.listBuckets() ;
	}
	
	@GetMapping(value = "/list")
	public Object list(FilePage filePage) {
		return this.ossClient.listObjects(filePage) ;
	}
	
}
